package com.yanyuan.snio.part;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

/**
 * @author: yanyuan
 * @Date: 2021/3/17 16:30
 * @Description:
 *
 * * 一、使用NIO完成网络通信的三个核心
 *  * 1.通道（Channel）:负责连接
 *  *      java.nio.channels.channel接口
 *  *      --SelectableChannel
 *  *      -- SocketChannel
 *  *      --ServerSocketChannel
 *  *      --DatagramChannel
 *  *
 *  *      -- Pipe.SinkChannel
 *  *      -- Pipe.SourceChannel
 *  * 2.缓存区（Buffer）:负责数据的存储
 *  * 3.选择器（selector）：是selectableChannel的多路复用器，用于监控SelectableChannel的IO状况
 *  *
 */
@Slf4j
public class NioP10NonBlock {

    public void client() throws IOException {
        //1.获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        //2.切换成非阻塞式
        socketChannel.configureBlocking(false);
        //3.分配指定大小缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);
        //4.发送时间
        List<String> msgs = Arrays.asList(new String[]{"你好", "在吗"});
        Iterator msgIterator = msgs.listIterator();
        while (msgIterator.hasNext()){
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            String msg = dateStr + " " + msgIterator.next();
            buf.put(msg.getBytes(StandardCharsets.UTF_8));
            buf.flip();
            socketChannel.write(buf);
            buf.clear();
        }

        //5.关闭通道
        socketChannel.close();
    }

    public void server() throws IOException {
        //1.获取通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //2.切换非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //3.绑定连接
        serverSocketChannel.bind(new InetSocketAddress(9898));
        //4.获取选择器
        Selector selector = Selector.open();
        //5.将通道注册到选择器上并指定”监听接收事件“(选择键：事件-读状态，写状态，连接状态，接收状态)
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //6.轮询式获取选择器已经“准备就绪”的事件
        while (selector.select() > 0){
            //7.获取当前选择器所有注册的“选择键（已就绪的监听事件）”
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();

            while (it.hasNext()){
                //8.获取准备“就绪”的事件
                SelectionKey key = it.next();
                //9.判断具体是什么事件准备就绪
                if(key.isAcceptable()){
                    //10.如果“接收就绪”，获取客户端连接
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    //11.切换非阻塞模式
                    socketChannel.configureBlocking(false);
                    //12.将该通道注册到选择器上
                    socketChannel.register(selector, SelectionKey.OP_READ);
                }else if(key.isReadable()){
                    //13.获取当前选择器“读就绪通道”
                    SocketChannel readChannel  = (SocketChannel) key.channel();
                    //14.读数据，缓冲区
                    ByteBuffer buf = ByteBuffer.allocate(1024);
                    int len = 0;
                    while ((len = readChannel.read(buf)) > 0){
                        buf.flip();
                        log.info("read: {}", new String(buf.array(), 0, len));
                        log.info("------");
                        buf.clear();
                    }
                }
                //15.取消选择键
                it.remove();
            }
        }

    }
}
